/**
 * Created by Freeman on 2018/2/9.
 */
import React from 'react'
import {FlatList, StyleSheet} from 'react-native'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import topicActions from '../../store/entities/topics/actions'
import TopicListRenderItem from "../base/TopicListRenderItem";
import AppLoading from "../base/AppLoading";


class ChannelView extends React.Component {

  constructor(props) {
    super(props)
    this.loadMoreTopic = this.loadMoreTopic.bind(this)
  }

  componentDidMount() {
    const {actions, id} = this.props
    actions.fetchTopics(id)
  }

  loadMoreTopic() {
    const {actions, topicsPagination, id} = this.props
    topicsPagination.hasMore && actions.fetchTopics(id, topicsPagination.number + 1)
  }

  render() {
    const {topics, navigation} = this.props
    if (topics.length === 0) {
      return <AppLoading/>
    }
    return (
      <FlatList
        data={topics}
        keyExtractor={(item, index) => item.id}
        renderItem={({item}) => <TopicListRenderItem item={item} navigation={navigation}/>}
        onEndReached={() => this.loadMoreTopic()}
      />
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
})


ChannelView.propTypes = {}

const mapStateToProps = (state, ownProps) => {
  const id = ownProps.id
  const {
    entities: {topics},
    pagination: {topicsByType}
  } = state

  const topicsPagination = topicsByType[id] || {ids: []}
  const topicsState = topicsPagination.ids.map(id => topics[id])
  return {
    topics: topicsState,
    topicsPagination
  }
}


const mapDispatchToProps = dispatch => (
  {
    actions: bindActionCreators(topicActions, dispatch)
  }
)

export default connect(mapStateToProps, mapDispatchToProps)(ChannelView)
